package com.bawei.module_play.vm

import com.bawei.lib_common.vm.BaseViewModel
import com.bawei.module_play.entriy.CommendEntity
import com.bawei.module_play.entriy.DanmuEntity
import com.bawei.module_play.intent.PlayVideoIntent
import com.bawei.module_play.repo.PlayVideoRepository
import com.bawei.module_play.state.PlayVideoState
import com.blankj.utilcode.util.GsonUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject

@HiltViewModel
class PlayViewModel @Inject constructor(private val repository:PlayVideoRepository):BaseViewModel<PlayVideoIntent>() {

    private val _uiStateFlow = MutableStateFlow<PlayVideoState>(PlayVideoState.LoadEmpty)
    val uiStateFlow: StateFlow<PlayVideoState> = _uiStateFlow.asStateFlow()

    override fun dispatchIntent(intent: PlayVideoIntent) {
        when(intent){
            is PlayVideoIntent.LoadAuthorInfo -> getAuthorById(intent.userId)
            is PlayVideoIntent.LoadRecommendSimpleVideo -> getRecommendSimpleVideo(intent.page, intent.pageSize)
            is PlayVideoIntent.LoadSimpleVideoByChannelId -> getSimpleVideoByChannelId(intent.channelId, intent.page, intent.pageSize)
            is PlayVideoIntent.LoadRecommendMultiVideo -> getRecommendMultiVideo(intent.page, intent.pageSize)
            is PlayVideoIntent.LoadMultiVideoByTypeId -> getMultiVideoByTypeId(intent.typeId, intent.page, intent.pageSize)
            is PlayVideoIntent.LoadVideoDanmuMsg -> getVideoDanmuMsg(intent.dataType, intent.itemId)
            is PlayVideoIntent.PublishVideoComment -> publishComment(intent.content)
            is PlayVideoIntent.PublishDanmuMsg -> publishDanmuMsg(intent.content)
            is PlayVideoIntent.LoadCommentByUserId -> getCommentByUserId(intent.dataType, intent.itemId)
        }
    }

    /**
     * 获取视频作者信息
     */
    private fun getAuthorById(userId: String){
        mViewModelScope.launch (mDispatcher) {
            repository.getAuthorId(userId).collectLatest {
                if (it != null){
                    _uiStateFlow.emit(PlayVideoState.LoadAuthorSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadAuthorFail("获取当前视频作者信息失败！！"))
                }
            }
        }
    }

    /**
     * 获取首页推荐视频
     */
    private fun getRecommendSimpleVideo(page: Int, pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendSimpleVideo(page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.LoadSimpleVideoSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadSimpleVideoFail("获取当前视频失败！！"))
                }
            }
        }

    }

    /**
     * 获取首页分类下视频
     */
    private fun getSimpleVideoByChannelId(channelId: String,page: Int,pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getSimpleVideoByChannelId(channelId, page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.LoadSimpleVideoSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadSimpleVideoFail("获取当前视频失败！！"))
                }
            }
        }
    }

    /**
     * 获取放映厅推荐视频
     */
    private fun getRecommendMultiVideo(page: Int,pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            repository.getRecommendMultiVideo(page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.LoadMultiVideoSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadMultiVideoFail("获取当前放映厅视频失败！！"))
                }
            }
        }

    }

    /**
     * 获取放映厅分类下视频
     */
    private fun getMultiVideoByTypeId(typeId: Int, page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            repository.getMultiVideoByTypeId(typeId, page, pageSize).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.LoadMultiVideoSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadMultiVideoFail("获取当前放映厅视频失败！！"))
                }
            }
        }
    }

    /**
     * 获取视频评论
     */
    private fun getCommentByUserId(dataType: Int, itemId: String){
        mViewModelScope.launch(mDispatcher) {
            repository.getCommentByUserId(dataType, itemId).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.LoadVideoCommentSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadVideoCommentFail("获取当前视频评论列表失败！！"))
                }
            }
        }

    }

    /**
     * 发送评论
     */
    private fun publishComment(str: CommendEntity){
        mViewModelScope.launch(mDispatcher) {
            //创建评论对象
            val toJson = GsonUtils.toJson(str)
            val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), toJson)
            //执行请求
            repository.publishComment(body).collectLatest {
                if (it != null){
                    _uiStateFlow.emit(PlayVideoState.PublishVideoCommentSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.PublishVideoCommentFail("发布视频评论失败！！"))
                }
            }
        }
    }

    /**
     * 发布弹幕
     */
    private fun publishDanmuMsg(danmu: String){
        mViewModelScope.launch(mDispatcher) {
            //创建评论对象
            var danmuEntity = DanmuEntity(
                content = danmu,
                datatype = 0,
            )

            //封装成RequestBody对象
            var body: RequestBody = GsonUtils.toJson(danmuEntity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

            repository.publishDanmuMsg(body).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.PublishVideoDanmuSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.PublishVideoDanmuFail("发送视频弹幕失败！！"))
                }
            }
        }
    }

    /**
     * 获取视频弹幕
     */
    private fun getVideoDanmuMsg(dataType: Int, itemId: String) {
        mViewModelScope.launch(mDispatcher) {
            repository.getVideoDanmuMsg(dataType, itemId).collectLatest {
                if (it.isNotEmpty()){
                    _uiStateFlow.emit(PlayVideoState.LoadVideoDanmuSuccess(it))
                } else {
                    _uiStateFlow.emit(PlayVideoState.LoadVideoDanmuFail("获取当前视频弹幕失败！！"))
                }
            }
        }

    }



}